package edu.mapi.ir.log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;

/**
 * @author ZP
 */
public class GameLogger {

	public static BufferedWriter bw;
	private static SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
	private static Hashtable<String, Integer> lastStates = new Hashtable<String, Integer>();
	public static boolean loggedSomething = false;
	
	public static boolean logMessage(String message, String UID, int time) {
		loggedSomething = true;
		if (lastStates.containsKey(UID) && lastStates.get(UID) == time)
			return false;
		
		lastStates.put(UID, time);
		
		return logMessage(message);
	}
	
	public static boolean logMessage(String message) {
		
		if (bw == null)
			startLog();
		
		if (bw != null) {
			try {
				bw.write(message+"<sync/>\n");
				return true;
			}
			catch (Exception e) {
				e.printStackTrace();
			}			
		}
		return false;
	}
	
	public static boolean startLog() {
		
		String timeStamp = timeFormat.format(new Date());
		String sep = System.getProperty("file.separator");		
		String dir = System.getProperty("user.dir")+sep+"logs";
		File f = new File(dir);	
		f.mkdirs();
		String filename = dir+sep+timeStamp+".log";
		try {
			bw = new BufferedWriter(new FileWriter(filename));	
			loggedSomething = false;
		}
		catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public static boolean resetLog() {
		return (endLog() && startLog());
	}
	
	public static boolean endLog() {
		if (bw != null) {
			try {
				bw.flush();
				bw.close();
			}
			catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		System.out.println("endlog");
		return true;
	}
}
